package cn.hiapi.shop.api;

import cn.hiapi.basic.ResponseEntity;
import cn.hiapi.basic.controller.BasicQueryController;
import cn.hiapi.basic.entity.BasicEntity;
import cn.hiapi.basic.exception.BasicException;
import cn.hiapi.basic.jpa.pageable.PageRequest;
import cn.hiapi.basic.jpa.pageable.QueryWrapper;
import cn.hiapi.basic.security.TokenGet;
import cn.hiapi.basic.service.BasicService;
import cn.hiapi.basic.token.Token;
import cn.hiapi.finance.entity.Amount;
import cn.hiapi.finance.service.AmountService;
import cn.hiapi.interfaces.DispatchContext;
import cn.hiapi.interfaces.finance.model.AmountModel;
import cn.hiapi.interfaces.user.IUserService;
import cn.hiapi.shop.entity.shop.Shop;
import cn.hiapi.shop.entity.shop.ShopLinkUser;
import cn.hiapi.shop.query.ShopUserQuery;
import cn.hiapi.shop.service.shop.ShopLinkUserService;
import cn.hiapi.shop.service.shop.ShopService;
import cn.hiapi.shop.vo.ActivityCardOrderVo;
import cn.hiapi.shop.vo.ShopUserVo;
import cn.hiapi.shopkeeper.consts.AppConst;
import cn.hiapi.shopkeeper.entity.order.ActivityCardOrder;
import cn.hiapi.shopkeeper.entity.shopkeeper.ShopUser;
import cn.hiapi.shopkeeper.service.order.ActivityCardOrderService;
import cn.hiapi.shopkeeper.service.order.ActivityOrderService;
import cn.hiapi.shopkeeper.service.shopkeeper.ShopUserService;
import cn.hiapi.user.entity.User;
import cn.hiapi.user.service.UserService;
import cn.hiapi.utils.JsonUtils;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author AdinZ
 * @date 2023/2/5 6:22
 */
@RestController
@RequestMapping("/shop-user")
public class ShopUserController extends BasicQueryController<ShopUser, Long, ShopUserVo, ShopUserQuery> {

    protected ShopUserController(ShopUserService basicService, DispatchContext dispatchContext) {
        super(basicService, dispatchContext);
    }

    @Override
    public ShopUserQuery setQuery(ShopUserQuery query) {
        Token<User> token = TokenGet.get();
        this.dispatchContext.getServiceOne(ShopLinkUserService.class).verifyShop(token.getFid(), query.getShopId());
        query.setShopId(query.getShopId());
        if (StringUtils.isNotEmpty(query.getMobile())) {
            Long uid = this.dispatchContext.getServiceOne(IUserService.class).getUid(0, query.getMobile());
            if (uid == null) throw new BasicException("手机号不存在");
            query.setUid(uid);
        }
        if (StringUtils.isNotEmpty(query.getNickname())) {
            List<User> users = this.dispatchContext.getServiceOne(UserService.class)
                    .findList(new QueryWrapper().like("nickname", "%" + query.getNickname() + "%"));
            if (users.isEmpty()) throw new BasicException("昵称不存在");
            query.setUids(users.stream().map(User::getId).collect(Collectors.toList()));
        }


        return super.setQuery(query);
    }

    @Override
    public List<ShopUserVo> toListVo(List<ShopUser> list, String[] fields) {
        return list.stream().map(e -> {
            ShopUserVo vo = e.copy(new ShopUserVo());
            User user = this.dispatchContext.getServiceOne(UserService.class).get(e.getUid());
            if (user != null) {
                vo.setNickname(user.getNickname());
                vo.setAvatar(user.getAvatar());
                vo.setMobile(user.getMobile());
            }
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public ShopUserVo toData(ShopUser data, String[] fields) {
        ShopUserVo vo = data.copy(new ShopUserVo());
        Token<User> token = TokenGet.get();
        this.dispatchContext.getServiceOne(ShopLinkUserService.class).verifyShop(token.getFid(), vo.getShopId());

        User user = this.dispatchContext.getServiceOne(UserService.class).get(data.getUid());
        if (user != null) {
            vo.setNickname(user.getNickname());
            vo.setAvatar(user.getAvatar());
            vo.setMobile(user.getMobile());
        }
        List<AmountModel> models = this.dispatchContext.getServiceOne(AmountService.class).findByFid(user.getId());
        JSONObject amount = new JSONObject();
        for (AmountModel model : models) {
            amount.put(model.getAmountType(), model.getAmount());
        }
        vo.setAmount(amount);

        long orderCount = this.dispatchContext.getServiceOne(ActivityOrderService.class).count(new QueryWrapper()
                .eq("buyerId", data.getUid()).eq("shopId", data.getShopId()).eq("statusType", 1));

        long cardCount = this.dispatchContext.getServiceOne(ActivityCardOrderService.class).count(new QueryWrapper()
                .eq("buyerId", data.getUid()).eq("shopId", data.getShopId()));
        JSONObject order = new JSONObject();
        order.put("orderCount", orderCount);
        order.put("cardCount", cardCount);
        vo.setOrder(order);
        return vo;
    }

    @ApiOperation(value = "更新用户资料", notes = "更新用户资料", nickname = "AdinZ")
    @PostMapping("/update")
    public ResponseEntity updateInfo(@RequestBody JSONObject data) {
        long id = data.getLongValue("id");
        ShopUser user = basicService.get(id);
        if (user == null) return toError("数据不存在");
        Token<User> token = TokenGet.get();
        this.dispatchContext.getServiceOne(ShopLinkUserService.class).verifyShop(token.getFid(), user.getShopId(), AppConst.SHOP_ROLE_EDIT_USER);

        Integer gender = data.getInteger("gender");
        if (gender != null) user.setGender(gender);
        Long birthday = data.getLong("birthday");
        if (birthday != null) user.setBirthday(birthday);
        String remark = data.getString("remark");
        if (StringUtils.isNotEmpty(remark)) {
            user.setRemark(remark);
        }
        this.basicService.save(user);
        return toSuccess();
    }


    @ApiOperation(value = "用户卡包列表", notes = "用户卡包列表", nickname = "AdinZ")
    @GetMapping("/card-list")
    public ResponseEntity cardList(@RequestParam("id") long id,
                                   @RequestParam("page") int page,
                                   @RequestParam(value = "status", required = false) Integer status) {
        ShopUser user = basicService.get(id);
        if (user == null) return toError("数据不存在");
        Token<User> token = TokenGet.get();
        this.dispatchContext.getServiceOne(ShopLinkUserService.class).verifyShop(token.getFid(), user.getShopId());
        ResponseEntity<List<ActivityCardOrder>> response = this.dispatchContext.getServiceOne(ActivityCardOrderService.class).findPage(new QueryWrapper()
                        .eq("buyerId", user.getUid()).eq("shopId", user.getShopId())
                        .eq("status", status),
                PageRequest.of(page, 20, Sort.Direction.DESC, "id")
        );
        Shop shop = this.dispatchContext.getServiceOne(ShopService.class).get(user.getShopId());
        List<ActivityCardOrderVo> collect = response.getData().stream().map(e -> {
            ActivityCardOrderVo vo = e.copy(new ActivityCardOrderVo());
            vo.setShop(JsonUtils.builder().put("name", shop.getName()).put("logo", shop.getLogo()).build());
            return vo;
        }).collect(Collectors.toList());
        return toSuccess(collect, response.getTotal(), response.getTotalPage());
    }


}
